<!-- 车次提货记录 -->
<template>
  <div class="train_pick_up_record">
    <el-card
      class="search_card h5Card"
      ref="searchCardRef">
      <el-form
        :model="formData"
        :rules="formRules"
        class="search_form">
        <el-row>
          <el-form-item label="提货主体公司">
            <el-select
              v-model="formData.baseCompanyId"
              placeholder="提货主体公司"
              style="width: 100%"
              clearable>
              <el-option
                v-for="item in baseCompanyList"
                :key="item.id"
                :label="item.simple_name"
                :value="item.id" />
            </el-select>
          </el-form-item>
          <el-form-item
            label="资金仓库名称"
            v-if="isExpand">
            <el-select
              v-model="formData.baseCapitalWarehouseId"
              placeholder="资金仓库名称"
              style="width: 100%"
              clearable>
              <el-option
                v-for="item in capitalWareHouseList"
                :key="item.id"
                :label="item.name"
                :value="item.id" />
            </el-select>
          </el-form-item>
          <el-form-item
            label="提货人"
            v-if="isExpand">
            <el-select
              v-model="formData.pickUserId"
              placeholder="提货人"
              style="width: 100%"
              clearable>
              <el-option
                v-for="item in userList"
                :key="item.id"
                :label="item.realName"
                :value="item.id" />
            </el-select>
          </el-form-item>
          <el-form-item
            label="提货日期"
            v-if="isExpand">
            <el-date-picker
              style="width: 100%"
              v-model="selectTime"
              format="YYYY-MM-DD"
              value-format="YYYY-MM-DD"
              type="daterange"
              range-separator="-"
              start-placeholder="开始时间"
              end-placeholder="结束时间" />
          </el-form-item>
          <el-form-item label="启用状态" 
            v-if="isExpand">
            <el-select
              v-model="formData.isEnable"
              placeholder="启用状态"
              style="width: 100%"
              clearable>
              <el-option
                :label="config.button.text.enable"
                :value="true" />
              <el-option
                label="作废"
                :value="false" />
            </el-select>
          </el-form-item>
        </el-row>
      </el-form>
      <div class="top-btn">
        <div
          class="expanded"
          @click="isExpand = !isExpand">
          <span v-if="!isExpand">
            <span>展开</span>
            <el-icon>
              <ArrowDown />
            </el-icon>
          </span>
          <span v-else>
            <span>收起</span>
            <el-icon>
              <ArrowUp />
            </el-icon>
          </span>
        </div>
        <div>
          <el-button
            v-permission="validateButtonPermission(route, 7)"
            type="success"
            @click="exportTable">
            导出表格
          </el-button>
          <el-button
            type="primary"
            @click="getList(formData)"
            class="search">
            <template #icon>
              <el-icon>
                <search />
              </el-icon>
            </template>
            {{ config.button.text.query }}
          </el-button>
          <el-button @click="reset">
            <template #icon>
              <el-icon>
                <Refresh />
              </el-icon>
            </template>
            {{ config.button.text.reset }}
          </el-button>
        </div>
      </div>
    </el-card>
    <div :style="{ height: tableHeight, overflow: 'auto' }">
      <el-card
        class="table_card info-card"
        v-if="tableData.length > 0"
        v-for="item in tableData"
        :key="item.id"
        @click="viewEvent(item)">
        <div class="info-item">
          <div class="info-title">提货主体公司：</div>
          <div class="info-main">{{ item.baseCompanySimpleName }}</div>
        </div>
        <div class="info-item">
          <div class="info-title">资金仓库名称：</div>
          <div class="info-main">{{ item.baseCapitalWarehouseName }}</div>
        </div>
        <div class="info-item">
          <div class="info-title">商品简称：</div>
          <div class="info-main">{{ item.baseRiceBarnGoodsSimpleName }}</div>
        </div>
        <div class="info-item">
          <div class="info-title">提货人：</div>
          <div class="info-main">{{ item.pickUserRealName }}</div>
        </div>
        <div class="info-item">
          <div class="info-title">提货日期：</div>
          <div class="info-main">{{ formatDate(item.pickDate) }}</div>
        </div>
        <div class="info-item">
          <div class="info-title">车次号：</div>
          <div class="info-main">{{ item.trainNumber }}</div>
        </div>
        <div class="info-item">
          <div class="info-title">提货完整吨数：</div>
          <div class="info-main">{{ item.pickIntactTon }}</div>
        </div>
        <div class="info-item">
          <div class="info-title">提货破损吨数：</div>
          <div class="info-main">{{ item.pickWornTon }}</div>
        </div>
        <div class="info-item">
          <div class="info-title">提货应付款：</div>
          <div class="info-main">{{ item.pickPayPrice }}</div>
        </div>
        <div class="info-item">
          <div class="info-title">是否启用：</div>
          <div class="info-main">
            <el-switch
              v-model="item.isEnable"
              inline-prompt
              active-text="启用"
              inactive-text="作废"
              @click.stop
              @change="(val) => changeState(val, item)" />
          </div>
        </div>
      </el-card>
      <noDataPage v-else />
    </div>
    <!-- 查看 -->
    <View
      ref="viewRef"
      :rowData="rowData"
      @pick-up="getBillLading"
      @edit-info="editEvent" />
    <!-- 新增修改 -->
    <Edit
      ref="editRef"
      :rowData="rowData"
      @save="save" />
    <!-- 生成提货单弹窗 -->
    <selectLadingBillTemplate
      :selectIds="selectIds"
      ref="selectDialogRef" />
  </div>
</template>

<script setup>
import { ref, onMounted, watch } from "vue";
import ApiCapitalWareHouse from "@/api/modules/capital-ware-house"
import ApiTrainPickRecord from "@/api/modules/train-pickRecord"
import { useTable } from "@/hooks/useTable"
import View from "./component/View.vue"
import Edit from "./component/Edit.vue"
import message from "@/common/element-plus/message";
import config from "@/common/element-plus/config";
import app from "@/common/config/app";
import { validateButtonPermission } from "@/common/utils/validate";
import { useRoute } from "vue-router"
import { useAppStore } from "@/stores/app"
import { storeToRefs } from "pinia";
import selectLadingBillTemplate from "./component/h5SelectLadingBillTemplate.vue";
import { formatDate } from "@/common/utils/date";
import ApiSysUser from "@/api/modules/sys-user"
import axios from "axios";
import noDataPage from "@/components/noDataPage.vue";
import { ElMessageBox } from "element-plus";

const route = useRoute()
// 查询表单
const formData = ref({})
// 查看组件实例
const viewRef = ref()
// 新增修改组件实例
const editRef = ref()
// 生成提货单弹窗实例
const selectDialogRef = ref()
// 表格每行数据
const rowData = ref({})
//选择的数据的id集合
const selectIds = ref(null)
// 表格高度(固定表头)
const height = ref(0)
// 查询卡片实例
const searchCardRef = ref()
// 资金仓库下拉框
const capitalWareHouseList = ref([])
const capitalWareHouseLoading = ref(false)
// 主体公司下拉框
const baseCompanyList = ref([])
//收缩展开
const isExpand = ref(false);
const selectTime = ref([]);
// const selectRows = ref(null);
//用户列表
const userList = ref([]);
//累计-提货应付款
const totalPayPrice = ref();
//token-请求头
const token = localStorage.getItem(localStorage.getItem("tokenName"))
const headers = ref({});
if (token) {
  headers.value["yg-token"] = token;
}
const tableHeight = ref("calc(100vh - 250px)")



const { tableMethods, tableState, pagination } = useTable({
  fetchDataApi: async (data) => {
    const { pageSize, pageNum } = pagination
    const res = await ApiTrainPickRecord.selectPage(data, {
      pageNum: pageNum.value,
      pageSize: pageSize.value,
    })
    getSumPickPayPrice();
    return {
      list: res.data.records,
      total: res.data.total
    }
  }
})
const { getList } = tableMethods
const { tableData } = tableState

//修改是否启用状态
const changeState = (newVal, row) => {
  ElMessageBox.confirm("确定要修改启用状态吗？", "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  }).then(async () => {
    const params = {
      id: row.id,
      isEnable: newVal
    }
    await ApiTrainPickRecord.changeState(params)
  }).catch(() => {
    row.isEnable = !newVal;
  });
}

//资金仓库列表
const getCapitalWareHouseSimpleNameList = async () => {
  capitalWareHouseLoading.value = true
  const data = await ApiCapitalWareHouse.getSimpleNameList("/baseCapitalWarehouse/")
  capitalWareHouseList.value = data.data
  capitalWareHouseLoading.value = false
}
getCapitalWareHouseSimpleNameList();

//主体公司列表
const getBaseCompanyList = async () => {
  const data = await ApiCapitalWareHouse.getSimpleNameList("/baseCompany/")
  baseCompanyList.value = data.data
}
getBaseCompanyList();

//获取用户列表
const getUserList = async () => {
  const pagination = {
    pageNum: 1,
    pageSize: -1
  }
  const res = await ApiSysUser.selectPage(null, pagination)
  userList.value = res.data.records;
}
getUserList();

// 处理选中行变化
// const handleSelectionChange = async (rows) => {
//   if (rows.length > 0) {
//     selectIds.value = rows.map(item => item.id);
//     selectRows.value = rows;
//   } else {
//     selectIds.value = null;
//     selectRows.value = null;
//   }
// };

const getSumPickPayPrice = async () => {
  const params = {
    pickUserId: formData.value.pickUserId,
    baseCompanyId: formData.value.baseCompanyId,
    baseCapitalWarehouseId: formData.value.baseCapitalWarehouseId,
    startPickDate: formData.value.startPickDate,
    endPickDate: formData.value.endPickDate
  }
  const res = await ApiTrainPickRecord.getSumPickPayPrice(params);
  totalPayPrice.value = res.data
}

//监听是否展开动态获取下面的高度
watch(() => isExpand.value, (newVal) => {
  if (newVal && isExpand.value) {
    setTimeout(() => {
      let searchCards = document.querySelector(".h5Card");
      tableHeight.value = `calc(100vh - 100px - ${searchCards.offsetHeight}px)`
    }, 200)
  } else {
    tableHeight.value = "calc(100vh - 205px)"
  }
}, { immediate: true })

//导出表格
const exportTable = async () => {
  ElMessageBox.confirm("确定要导出表格吗？", "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  }).then(async () => {
    const params = {
      pickUserId: formData.value.pickUserId || "",
      baseCompanyId: formData.value.baseCompanyId || "",
      baseCapitalWarehouseId: formData.value.baseCapitalWarehouseId || "",
      startPickDate: formData.value.startPickDate || "",
      endPickDate: formData.value.endPickDate || ""
    }

    //先判断是否有数据能够导出
    const res = await axios.post(`${import.meta.env.VITE_API}/trainPickRecord/export`, params, {
      responseType: "application/json",
      headers: {
        "yg-token": token  // 根据后端要求设置 Token 头部
      }
    });
    if (!res.data.includes("message")) {
      const response = await axios.post(`${import.meta.env.VITE_API}/trainPickRecord/export`, params, {
        responseType: "blob", // 指定响应类型为 Blob
        headers: {
          "yg-token": token  // 根据后端要求设置 Token 头部
        }
      });
      const contentDisposition = response.headers["content-disposition"];
      let fileName = "文件.xlsx";
      if (contentDisposition && contentDisposition.includes("filename=")) {
        fileName = contentDisposition
          .split("filename=")[1]
          .split(";")[0]
          .replace(/['"]/g, "");
        fileName = decodeURIComponent(fileName)
      }

      const blob = new Blob([response.data], {
        type: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
      });

      const link = document.createElement("a");
      link.href = URL.createObjectURL(blob);
      link.download = fileName;
      document.body.appendChild(link);
      link.click();
      document.body.removeChild(link);
      URL.revokeObjectURL(link.href);
    } else {
      message.warning("导出的数据为空")
    }
  })
}
// 监听时间选择
watch(() => selectTime.value, (newVal) => {
  if (newVal) {
    if (Array.isArray(newVal) && newVal.length === 2) {
      formData.value.startPickDate = newVal[0];
      formData.value.endPickDate = newVal[1];
    }
  } else {
    formData.value.startPickDate = "";
    formData.value.endPickDate = "";
  }
}, { immediate: true })
// 重置
const reset = () => {
  formData.value = {}
  selectTime.value=""
  getList()
}

// 打开查看对话框
const viewEvent = (row) => {
  viewRef.value.visibility = true
  rowData.value = row
}

// 打开新增对话框
const getBillLading = (ids) => {
  if (ids) {
    selectIds.value = ids;
  }
  if (!selectIds.value) {
    message.warning("请至少选择一条数据!");
    return;
  }
  selectDialogRef.value.visibility = true
  // rowData.value = {}
}

// 打开修改对话框
const editEvent = (row) => {
  editRef.value.visibility = true
  rowData.value = Object.assign({}, row)
}

// 保存后回调
const save = async () => {
  editRef.value.visibility = false
  message.success()
  // await getList()
}

// 监听查询卡片大小变化
const resizeObserver = new ResizeObserver(entries => {
  for (const entry of entries) {
    if (contentFullScreen.value) {
      height.value = (window.innerHeight - app.otherHeight - app.tagHeight - entry.contentRect.height) + "px"
    } else {
      height.value = (window.innerHeight - app.otherHeight - app.tagHeight - app.headerHeight - entry.contentRect.height) + "px"
    }
  }
})

const appStore = useAppStore()

// 保持响应式
const { contentFullScreen } = storeToRefs(appStore)

onMounted(() => {
  resizeObserver.observe(searchCardRef.value.$el)
})
</script>

<style lang="scss" scoped>
.train_pick_up_record {
  .search_card {
    margin-bottom: 4px;

    :deep(.el-card__body) {
      padding: 10px;
      // display: flex;
      justify-content: space-between;
    }

    .el-button {
      margin: 5px 10px 5px 0;
    }

    .el-form-item {
      margin-right: 10px;
      padding: 5px 0;
    }

    .top-btn {
      margin-top: 5px;
      display: flex;
      align-items: center;
      justify-content: space-between;
    }
  }

  .expanded {
    margin-right: 10px;
    text-align: right;
    color: #e6a23c;

    span {
      font-size: 14px;
    }
  }

  .table_card {
    :deep(.el-card__body) {
      padding: 0;
    }
  }

  .info-card {
    padding: 10px;
    margin-bottom: 3px;

    .info-item {
      display: flex;
      padding: 5px 0;

      .info-title {
        min-width: 120px;
        color: #999;
      }

      .info-main {
        flex: 1;
        white-space: nowrap;
        overflow: hidden;
        text-overflow: ellipsis;
      }
    }
  }
}

.top-btn {
  text-align: right;
  color: #409eff;

  .top-btn-item {
    // display: flex;
    // align-items: center;
    margin-right: 5px;
  }
}

:deep(.el-form-item__label) {
  min-width: 100px;
}

.el-form-item {
  width: 100%;
}
</style>